package com.i_art_engineer.meigong.activity;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.DisplayMetrics;
import android.view.View;
import android.widget.Button;

import com.i_art_engineer.meigong.R;
import com.i_art_engineer.meigong.base.FullScreenFragmentActivity;
import com.i_art_engineer.meigong.fragment.PhotoSelectorFragment;
import com.i_art_engineer.meigong.util.DimenUtils;

import java.io.File;
import java.util.ArrayList;

/**
 * 多图选择界面
 */
public class PhotoSelectorActivity extends FullScreenFragmentActivity implements PhotoSelectorFragment.Callback {

    /**
     * 最大图片选择次数，int类型，默认9
     */
    public static final String EXTRA_SELECT_COUNT = "max_select_count";
    /**
     * 图片选择模式，默认多选
     */
    public static final String EXTRA_SELECT_MODE = "select_count_mode";

    /**
     * 是否多选新增模式,只返回新增选的图片，已选图片无法撤销选择。
     */
    public static final String EXTRA_APPEND_IMAGES_MODE = "append_images_mode";

    /**
     * 是否显示相机，默认显示
     */
    public static final String EXTRA_SHOW_CAMERA = "show_camera";
    /**
     * 选择结果，返回为 ArrayList&lt;String&gt; 图片路径集合
     */
    public static final String EXTRA_RESULT = "select_result";
    /**
     * 默认选择集
     */
    public static final String EXTRA_DEFAULT_SELECTED_LIST = "default_list";

    /**
     * 单选
     */
    public static final int MODE_SINGLE = 0;
    /**
     * 多选
     */
    public static final int MODE_MULTI = 1;

    /**
     * 屏幕高度
     */
    public static int screenHeight = 0;
    public static int screenWidth = 0;
    public static int dx2 = 0;

    private ArrayList<String> mustList = new ArrayList<>(); //多选增加模式
    private ArrayList<String> resultList = new ArrayList<>();
    private Button mSubmitButton;
    private int mDefaultCount;
    private boolean isAppendMode = false;
    public PhotoSelectorFragment mfragment;
    private Dialog exitDialog = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_photo_selector);


        DisplayMetrics dm = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(dm);
        screenHeight = dm.heightPixels;
        screenWidth = dm.widthPixels;

        dx2 = DimenUtils.dp2px(PhotoSelectorActivity.this, 65);

        Intent intent = getIntent();
        mDefaultCount = intent.getIntExtra(EXTRA_SELECT_COUNT, 9);
        int mode = intent.getIntExtra(EXTRA_SELECT_MODE, MODE_MULTI);
        boolean isShow = intent.getBooleanExtra(EXTRA_SHOW_CAMERA, true);
        if (mode == MODE_MULTI) {
            isAppendMode = intent.getBooleanExtra(EXTRA_APPEND_IMAGES_MODE, false);
        }
        if (mode == MODE_MULTI && intent.hasExtra(EXTRA_DEFAULT_SELECTED_LIST)) {
            resultList = intent.getStringArrayListExtra(EXTRA_DEFAULT_SELECTED_LIST);
            if (isAppendMode) mustList = (ArrayList) resultList.clone();
        }

        Bundle bundle = new Bundle();
        bundle.putInt(PhotoSelectorFragment.EXTRA_SELECT_COUNT, mDefaultCount);
        bundle.putInt(PhotoSelectorFragment.EXTRA_SELECT_MODE, mode);
        bundle.putBoolean(PhotoSelectorFragment.EXTRA_SHOW_CAMERA, isShow);
        if (isAppendMode) {
            bundle.putStringArrayList(PhotoSelectorFragment.EXTRA_DEFAULT_MUST_SELECTED_LIST, mustList);
        }
        bundle.putStringArrayList(PhotoSelectorFragment.EXTRA_DEFAULT_SELECTED_LIST, resultList);
        mfragment = (PhotoSelectorFragment) Fragment.instantiate(this, PhotoSelectorFragment.class.getName(), bundle);
        getSupportFragmentManager().beginTransaction()
                .add(R.id.image_grid, mfragment)
                .commit();

        // 返回按钮
        findViewById(R.id.btn_back).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
//                    setResult(RESULT_CANCELED);
                String catalog = mfragment.mCategoryText.getText().toString();
                if ("所有照片".equals(catalog)) {
                    finish();
                } else if (mfragment.mFolderPopupWindow.isShowing()) {
                    mfragment.mFolderPopupWindow.dismiss();
                    finish();
                } else {
                    mfragment.mFolderPopupWindow.show();
                }
            }
        });

        // 完成按钮
        mSubmitButton = (Button) findViewById(R.id.commit);
        if (resultList == null || resultList.size() <= 0) {
            mSubmitButton.setText(R.string.action_done);
            mSubmitButton.setEnabled(false);
        } else {
            updateDoneText();
            mSubmitButton.setEnabled(true);
        }
        mSubmitButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (resultList != null && resultList.size() > 0) {
                    // 返回已选择的图片数据

                    if (isAppendMode) {
                        resultList.removeAll(mustList);
                        Intent data = new Intent();
                        data.putStringArrayListExtra(EXTRA_RESULT, resultList);
                        setResult(RESULT_OK, data);
                        finish();
                    }
                    else {
                        MainActivity.is_can_free = true;
                        MainActivity.is_can_scrool = false;
                        Intent intent = new Intent(PhotoSelectorActivity.this, PhotoEditorActivity.class);
                        intent.putStringArrayListExtra(PhotoEditorActivity.EXTRA_SELECTED_IMAGES, resultList);

                        startActivity(intent);
                    }




                }
            }
        });
    }

    private void updateDoneText() {
        mSubmitButton.setText(String.format("%s(%d/%d)", getString(R.string.action_done), resultList.size(), mDefaultCount));
    }

    @Override
    public void onSingleImageSelected(String path) {
        Intent data = new Intent();
        resultList.add(path);
        data.putStringArrayListExtra(EXTRA_RESULT, resultList);
        setResult(RESULT_OK, data);
        finish();
    }

    @Override
    public void onImageSelected(String path) {
        if (!resultList.contains(path)) {
            resultList.add(path);
        }
        // 有图片之后，改变按钮状态
        if (resultList.size() > 0) {
            updateDoneText();
            if (!mSubmitButton.isEnabled()) {
                mSubmitButton.setEnabled(true);
            }
        }
    }

    @Override
    public void onImageUnselected(String path) {
        if (resultList.contains(path)) {
            resultList.remove(path);
        }
        updateDoneText();
        // 当为选择图片时候的状态
        if (resultList.size() == 0) {
            mSubmitButton.setText(R.string.action_done);
            mSubmitButton.setEnabled(false);
        }
    }

    @Override
    public void onCameraShot(File imageFile) {
        if (imageFile != null) {
            // notify system
            sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(imageFile)));

            Intent data = new Intent();
            resultList.add(imageFile.getAbsolutePath());
            data.putStringArrayListExtra(EXTRA_RESULT, resultList);
            setResult(RESULT_OK, data);
            finish();
        }
    }

    public void showExitDialog(){
        AlertDialog.Builder builder=new AlertDialog.Builder(this);

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

    }
}
